package day12;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class ProduceConsumerLockDemo {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
			
	}

}
/**
 * JDK1.5中提供了多线程升级解决方案
 * 将同步synchronized替换成了显式的Lock操作
 * 将Object中的wait、notify、notifyAll替换成了Condition对象
 * Condition对象可以通过Lock的newCondition方法获取
 * 该示例中，实现了本方只唤醒对方的操作
 * @author wangbiao
 *
 */
class LockResource {
	
	private String name;
	
	private int count;
	
	private boolean flag = false;
	
	private Lock lock = new ReentrantLock();
	
	private Condition producerCon = lock.newCondition();
	
	private Condition consumerCon = lock.newCondition();
	
	public void set(String name) {
		//加锁，同步
		lock.lock();
		
		try {
			while (flag) {
				producerCon.await();
			}
			this.name = name + "....." +this.count;
			System.out.println(Thread.currentThread().getName()+name+"...生产者..."+this.name);
			flag = true;
			//唤醒消费者线程
			consumerCon.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			//释放锁
			lock.unlock();
		}
	}
	
	public void out() {
		lock.lock();
		try {
			while (!flag) {
				consumerCon.await();
			}
			System.out.println(Thread.currentThread().getName()+"......消费者......."+this.name);
			flag = false;
			producerCon.signal();
		} catch (InterruptedException e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
	}
	
}
